package com.hcloud.auth.api.token;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hcloud.common.core.constants.AuthConstants;
import com.hcloud.system.core.bean.user.User;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 解析jwt并将信息放入Authentication
 *
 * @Auther hepangui
 * @Date 2018/11/14
 */
public class AdditionalUserAuthenticationConverter extends DefaultUserAuthenticationConverter {

    @Override
    public Authentication extractAuthentication(Map<String, ?> map) {
        if (map.containsKey(AuthConstants.USER)) {
            Object object = map.get(AuthConstants.USER);
            User user = null;
            if (object != null) {
                user = JSONObject.parseObject(JSONObject.toJSONString(object), User.class);
            }
            Set<GrantedAuthority> set = new HashSet<>();
            Object o = map.get(AuthConstants.AUTHORITY);
            if (o != null) {
                List<String> strings = JSONArray.parseArray(JSONArray.toJSONString(map.get(AuthConstants.AUTHORITY)), String.class);
                strings.forEach(auth -> set.add(new SimpleGrantedAuthority(auth)));
            }
            return new UsernamePasswordAuthenticationToken(user, "N/A", set);
        }
        return null;
    }


}
